package com.egao.common.publicly.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.module.guidance.entity.Lecture;
import com.egao.common.module.guidance.mapper.LectureMapper;
import com.egao.common.module.guidance.service.LectureApplyService;
import com.egao.common.module.student.entity.Student;
import com.egao.common.module.student.service.StudentService;
import com.egao.common.publicly.entity.ApplyButtonVO;
import com.egao.common.publicly.entity.LectureVO;
import com.egao.common.publicly.mapper.PubliclyLectureMapper;
import com.egao.common.publicly.service.PubliclyLectureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * 首页讲座接口实现类
 *
 * @author pyx
 */
@Service
public class PubliclyLectureServiceImpl extends ServiceImpl<PubliclyLectureMapper, Lecture> implements PubliclyLectureService {
    @Autowired
    private StudentService studentService;
    @Autowired
    private LectureApplyService lectureApplyService;

    @Override
    public List<LectureVO> listPage(PageParam<LectureVO> pageParam) {
        return baseMapper.listPage(pageParam);
    }

    @Override
    public JsonResult getId(Integer userId, Integer id) {

        Lecture lecture = baseMapper.getId(id);

        ApplyButtonVO applyButton = new ApplyButtonVO();
        ApplyButtonVO cancelButton = new ApplyButtonVO();
        cancelButton.setButtonText("取消");

        if (lecture == null) {
            return JsonResult.ok("讲座暂无信息");
        }

        //先判断是否登录了
        if (userId == null) {
            applyButton.setButtonState(2);
            applyButton.setButtonText("未登录");
            cancelButton.setButtonState(2);
            return JsonResult.ok("未登录").setData(lecture).put("applyButton", applyButton).put("cancelButton", cancelButton);
        }

        //判断登录后的情况
        Student student = studentService.getByUserId(userId);
        if (student == null) {
            applyButton.setButtonState(2);
            applyButton.setButtonText("非学生账号不能报名");
            cancelButton.setButtonState(2);
            return JsonResult.ok("学生账号不存在").setData(lecture).put("applyButton", applyButton).put("cancelButton", cancelButton);
        }

        JsonResult jsonResult = lectureApplyService.applyVerify(lecture.getId(), student.getId());

        //更新讲座点击量
        if (lecture.getHits() == null) {
            lecture.setHits(0);
        }
        lecture.setHits(lecture.getHits() + 1);
        baseMapper.updateById(lecture);

        return jsonResult.setData(lecture);
    }

    @Override
    public Integer allHists(HashMap<String, String> createTimeMap) {
        return baseMapper.allHists(createTimeMap);
    }
}
